<template>
  <div class="app-container site-edit-container">
    <!-- 信息卡片 -->
    <el-card class="info-card">
      <!-- 站点信息 -->
      <el-descriptions :title="detailInfo.siteName" column="1">
        <el-descriptions-item label="创建时间">{{
          detailInfo.createTime
        }}</el-descriptions-item>
        <el-descriptions-item label="行政区划">{{
          detailInfo.region
        }}</el-descriptions-item>
        <el-descriptions-item label="详细地址">{{
          detailInfo.detailAddress
        }}</el-descriptions-item>
        <div slot="extra">
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleEdit">修改</el-button>
        </div>
      </el-descriptions>

      <div class="map-container" id="map" style="width: 100%; height: 300px"> </div>

      <!-- 运营信息 -->
      <el-descriptions style="margin-top: 30px" title="运营信息" column="1">
        <el-descriptions-item label="运营收入(元)" :labelStyle="{ 'font-size': '14px', 'line-height': '30px' }"
          contentStyle="font-weight: bold; font-size: 30px; line-height: 30px">{{ detailInfo.incomeNumber
          }}</el-descriptions-item>
        <el-descriptions-item label="今日收入">
          <div slot="label" style="display: flex; align-items: center">
            <div class="point primary" style="margin-right: 5px"></div>
            今日收入
          </div>
          {{ detailInfo.incomeNumber }} 元
        </el-descriptions-item>
        <el-descriptions-item label="今日充电时长">
          <div slot="label" style="display: flex; align-items: center">
            <div class="point danger" style="margin-right: 5px"></div>
            今日充电时长
          </div>
          {{ formatDuration(detailInfo.todayChargeTimeNumber) }}
        </el-descriptions-item>
        <el-descriptions-item label="今日充电次数">
          <div slot="label" style="display: flex; align-items: center">
            <div class="point warning" style="margin-right: 5px"></div>
            今日充电次数
          </div>
          {{ detailInfo.todayChargeCountNumber }} 次
        </el-descriptions-item>
        <el-descriptions-item label="今日充电量">
          <div slot="label" style="display: flex; align-items: center">
            <div class="point success" style="margin-right: 5px"></div>
            今日充电量
          </div>
          {{ detailInfo.todayChargeCapacity / 1000 }} 度
        </el-descriptions-item>
        <!-- <el-descriptions-item label="收费模式">{{
          chargeModeMap[chargeStrategy.chargeMode] || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="扫码/储值套餐收费">{{
          chargeStrategy.scanChargeRuleConfig
            ? billTypeMap[chargeStrategy.scanChargeRuleConfig.billType] || "-"
            : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="实体卡-消费卡收费">{{
          chargeStrategy.cardChargeRuleConfig
            ? billTypeMap[chargeStrategy.cardChargeRuleConfig.billType] || "-"
            : "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="实体卡-次数卡收费"
          >xxxx小时/次</el-descriptions-item
        > -->
      </el-descriptions>
    </el-card>
    <!-- 表格卡片 -->
    <el-card class="table-card">
      <el-tabs v-model="tab_name">
        <!-- 设备table -->
        <el-tab-pane label="设备" name="device">
          <el-card style="margin-bottom: 20px" body-style="display: flex; align-items: center;">
            <div class="stat-content">
              <el-row>
                <el-col :span="6" class="stat-item">
                  <el-statistic title="设备总数" :value="statInfo.siteNumber"></el-statistic>
                </el-col>
                <el-col :span="6" class="stat-item">
                  <el-statistic title="在线设备" :value="statInfo.onlineSiteNumber">
                    <template slot="prefix">
                      <div class="point success"></div>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6" class="stat-item">
                  <el-statistic title="离线设备" :value="statInfo.offlineSiteNumber">
                    <template slot="prefix">
                      <div class="point danger"></div>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6" class="stat-item">
                  <el-statistic title="未注册设备" :value="statInfo.unRegisterSiteNumber">
                    <template slot="prefix">
                      <div class="point info"></div>
                    </template>
                  </el-statistic>
                </el-col>
              </el-row>
            </div>
            <div class="divider"></div>
            <div class="stat-content">
              <el-row>
                <el-col :span="6" class="stat-item">
                  <el-statistic title="设备总数" :value="statInfo.siteNumber">
                  </el-statistic>
                </el-col>
                <el-col :span="6" class="stat-item">
                  <el-statistic title="正常设备" :value="statInfo.normalSiteNumber">
                    <template slot="prefix">
                      <div class="point success"></div>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6" class="stat-item">
                  <el-statistic title="故障设备" :value="statInfo.breakDownSiteNumber">
                    <template slot="prefix">
                      <div class="point danger"></div>
                    </template>
                  </el-statistic>
                </el-col>
              </el-row>
            </div>
          </el-card>

          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
            <el-form-item label="设备名称/序列号" prop="stationName">
              <el-input v-model="queryParams.stationName" placeholder="请输入设备名称/序列号" clearable style="width: 240px"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['system:role:add']"
                >新增</el-button
              >
            </el-col>
            <right-toolbar
              @queryTable="getList"
            ></right-toolbar>
          </el-row> -->

          <el-table v-loading="loading" :data="roleList">
            <el-table-column label="设备id" prop="id" width="200" />
            <el-table-column label="站点名称" prop="siteName" width="150" />
            <el-table-column label="设备名称" prop="stationName" width="150" />
            <el-table-column label="设备类型" prop="deviceType" width="150" />
            <el-table-column label="序列号" prop="deviceSerialNum" width="150" />
            <el-table-column label="设备状态" prop="deviceStatus" width="150">
              <template slot-scope="scope">
                <span>{{ deviceStatusMap[scope.row.deviceStatus] }}</span>
              </template>
            </el-table-column>
            <el-table-column label="在线状态" prop="onlineStatus" width="150">
              <template slot-scope="scope">
                <span>{{ onlineStatusMap[scope.row.onlineStatus] }}</span>
              </template>
            </el-table-column>
            <el-table-column label="到期时间" prop="expireTime" width="180" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="160">
              <template slot-scope="scope" v-if="scope.row.roleId !== 1">
                <el-button size="mini" type="text" icon="el-icon-search" @click="toDetail(scope.row)">详情</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:role:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-tab-pane>
        <!-- 收费模式 -->
        <el-tab-pane label="收费模式" name="config">
          <ChargeStrategyDesc :chargeForm="chargeStrategy"></ChargeStrategyDesc>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 修改站点 -->
    <EditModal title="修改站点" :data="detailInfo" :visible="editVisible" @success="onEditSuccess" @cancel="onEditCancel">
    </EditModal>
  </div>
</template>
<script>
import EditModal from "./components/EditModal";
import ChargeStrategyDesc from "@/components/ChargeStrategyDesc";
import { getDetailAPI, getStatisticAPI } from "@/api/charge/site";
import { getListAPI, addOrUpdateAPI, deleteAPI } from "@/api/charge/station";
import moment from "moment";
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  components: { EditModal, ChargeStrategyDesc },
  data() {
    return {
      tab_name: "device",
      siteId: "",
      editVisible: false,

      // 站点详情
      detailInfo: {},
      // 统计数据详情
      statInfo: {},
      // 站点充电策略
      chargeStrategy: {},

      chargeModeMap: {
        FREE: "免费",
        FEE: "收费",
      },
      billTypeMap: {
        ELEC: "电量收费",
        FIXED: "固定收费",
        STEP: "阶梯收费",
      },
      deviceStatusMap: {
        NORMAL: "正常",
        BREAK: "故障",
      },
      onlineStatusMap: {
        ONLINE: "在线",
        OFFLINE: "离线",
        UNREGISTER: "未注册",
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationName: "",
        siteId: "",
      },
      roleList: [],
      total: 0,
      loading: false,

      map: null,
      icons: {
        normal:
          "https://charging-mini.oss-cn-hangzhou.aliyuncs.com/charging-mini/test/user/1852264564548263937/1731581064963-awpsbiF4Ud5Nf090f4bce487db9893e2d5f5e3f97e9f.png",
        selected:
          "https://charging-mini.oss-cn-hangzhou.aliyuncs.com/charging-mini/test/user/1852264564548263937/1731656568429-nGDU4DDtF6Kl008ca122a9ac084ec802a913e1156591.png",
      },
    };
  },
  created() {
    this.siteId = this.$route.query.id;
    this.queryParams.siteId = this.$route.query.id;

    this.getDetail();
    this.getStatistic();
    this.getList();
  },
  methods: {
    // 地图初始化
    initAMap(params) {
      window._AMapSecurityConfig = {
        securityJsCode: "c860797e18c8a6d07dbf9b7d802ef3d4",
      };
      AMapLoader.load({
        key: "013dc7ef41f35fe78a6562c0e73b08d9", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          this.createMap(params);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // 绘制地图
    createMap(params) {
      let { longitude, latitude } = params;

      // 检查经纬度是否有效
      if (!longitude || !latitude) {
        console.error('Invalid longitude or latitude');
        return;
      }

      try {
        this.map = new AMap.Map("map", {
          // mapStyle: "amap://styles/blue",
          // 设置地图容器id
          viewMode: "3D", // 是否为3D地图模式
          zoom: 11, // 初始化地图级别
          center: [longitude, latitude], // 初始化地图中心点位置
          features: ["bg", "road", "building", "point"],
        });

        // 普通icon
        const normalIcon = new AMap.Icon({
          size: new AMap.Size(42, 42), //图标尺寸
          image: this.icons.normal,
          imageOffset: new AMap.Pixel(0, 0), //图像相对展示区域的偏移量，适于雪碧图等
          imageSize: new AMap.Size(42, 42), //根据所设置的大小拉伸或压缩图片
        });

        const marker = new AMap.Marker({
          position: new AMap.LngLat(longitude, latitude),
          icon: normalIcon,
          title: '当前位置',
        });

        this.map.add(marker);

      } catch (error) {
        console.error('Map initialization error:', error);
      }
    },
    formatDuration(time) {
      // 参数time单位为分钟，转为秒
      let d = moment.duration(time * 60 * 1000);
      let seconds = d.seconds();
      let minutes = d.minutes();
      let hours = d.hours();
      let days = d.days();
      return `${days ? days + "天" : ""}${hours ? hours + "小时" : ""}${minutes ? minutes + "分钟" : ""
        }${seconds ? seconds + "秒" : ""}`;
    },
    // 编辑成功回调
    onEditSuccess() {
      this.getStatistic();
      this.getDetail();
      this.editVisible = false;
    },
    // 编辑关闭回调
    onEditCancel() {
      this.editVisible = false;
    },
    // 修改站点信息
    handleEdit() {
      this.editVisible = true;
    },
    // 查询站点详情
    getDetail() {
      getDetailAPI({ id: this.siteId }).then((res) => {
        this.detailInfo = res.data || {};
        this.chargeStrategy = this.detailInfo.chargeStrategy
          ? JSON.parse(this.detailInfo.chargeStrategy)
          : {};

        this.$nextTick(() => {
          this.initAMap({
            latitude: this.detailInfo.latitude,
            longitude: this.detailInfo.longitude,
          });
        });
      });
    },
    // 查询数据
    getStatistic() {
      getStatisticAPI({ siteId: this.siteId }).then((res) => {
        this.statInfo = res.data;
      });
    },
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      getListAPI(this.queryParams).then((res) => {
        this.roleList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 跳转设备详情页 */
    toDetail(row) {
      this.$router.push({
        path: "/charge/station/edit",
        query: {
          stationName: row.stationName,
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.map-container {
  background-color: #efefef;
}

.site-edit-container {
  display: flex;
}

.info-card {
  height: 100%;
  width: 20%;
  overflow: auto;
  margin-right: 20px;
  flex: 1;
}

.table-card {
  height: 100%;
  width: 80%;
  overflow: auto;
  flex: 3;

  .stat-content {
    width: 50%;
    flex: auto;

    .stat-item {
      margin: 5px 0;
    }
  }

  .divider {
    flex: none;
    height: 60px;
    width: 1px;
    background-color: #efefef;
    margin: 0 20px;
  }
}

.point {
  width: 8px;
  height: 8px;
  border-radius: 50%;

  &.primary {
    background-color: #409eff;
  }

  &.success {
    background-color: #67c23a;
  }

  &.warning {
    background-color: #e6a23c;
  }

  &.danger {
    background-color: #f56c6c;
  }

  &.info {
    background-color: #909399;
  }
}
</style>
